from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.serializers import Serializer
from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from apps.meiduo_admin.serializers.sku import SKUSerializer, ThreeCategorySerializer, SimpleSPUSerializer, \
    SPUSpecsSerializer
from apps.meiduo_admin.utils import PageNum


class SKUModelViewSet(ModelViewSet):
    # 属性设置 就是返回固定的数据
    # queryset = SKU.objects.all()
    # 查询数据，有指定查和查所有，所以需要分成２种情况来写
    # 重写查询集
    def get_queryset(self):
        key = self.request.query_params.get('keyword')
        if key:
            # 返回模糊查询的结果
            return SKU.objects.filter(name__contains=key)
        else:
            # 返回未指定所有结果
            return SKU.objects.all()

    # 创建序列化器
    serializer_class = SKUSerializer
    # 分页
    pagination_class = PageNum


# 获取三级分类
class ThreeCategoryListAPIView(ListAPIView):
    # 这里是通过subs =None 来确定三级分类的，因为三级分类没有子类
    queryset = GoodsCategory.objects.filter(subs=None)
    # 序列化器
    serializer_class = ThreeCategorySerializer


# 获取SPU
class SimpleSPUListAPIView(ListAPIView):
    # 查询所有SPU名称
    queryset = SPU.objects.all()
    # 创建序列化器
    serializer_class = SimpleSPUSerializer


# 获取spu规格选项
class SPUSpecsAPIView(APIView):
    def get(self, request, pk):
        # 通过spu的id获取商品的规格
        specs = SPUSpecification.objects.filter(spu_id=pk)
        # 序列化器
        serializer = SPUSpecsSerializer(specs, many=True)
        return Response(serializer.data)
